<script setup lang="ts">
import { computed, watch } from 'vue';
import { useForm } from '@sa/alova/client';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { createSite, updateSite } from '@/service/api/cms';
import { $t } from '@/locales';

defineOptions({
  name: 'SiteDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Model | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增站点',
    edit: '编辑站点'
  };
  return titles[props.operateType];
});

const {
  loading: submitting,
  reset,
  send: submit,
  form,
  updateForm
} = useForm(formData => (props.operateType === 'add' ? createSite(formData) : updateSite(formData)), {
  initialForm: {
    id: 0,
    name: null,
    slug: null,
    domain: null,
    seoTitle: null,
    seoKeyword: null,
    seoDescription: null,
    creator: null,
    createTime: null,
    updater: null,
    updateTime: null,
    status: null,
    template: null,
    extendProp: null
  } as Api.Model,
  resetAfterSubmitting: true
});

type RuleKey = Extract<keyof Api.Model, 'userName' | 'status'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  userName: defaultRequiredRule,
  status: defaultRequiredRule
};

function handleInitModel() {
  if (props.operateType === 'edit' && props.rowData) {
    updateForm(props.rowData);
  } else if (props.operateType === 'add') {
    reset();
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  // request
  await submit();
  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    restoreValidation();
    handleInitModel();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="form" :rules="rules">
        <NFormItem label="站点名称" path="name">
          <NInput v-model:value="form.name" placeholder="站点名称" />
        </NFormItem>
        <NFormItem label="站点地址" path="domain">
          <NInput v-model:value="form.domain" placeholder="站点地址" />
        </NFormItem>
        <NFormItem label="模板" path="templateId">
          <PorSelect
            v-model:value="form.templateId"
            placeholder="请选择模板"
            url="/cms/template/simpleList?status=1"
            label-field="name"
            value-field="id"
            value-to-number
            filterable
            size="small"
          ></PorSelect>
        </NFormItem>
        <NFormItem label="是否启用" path="status">
          <PorDictRadio v-model:value="form.status" dict-code="common_yes_no" value-to-number></PorDictRadio>
        </NFormItem>
        <NFormItem label="是否主站" path="master">
          <PorDictRadio v-model:value="form.master" dict-code="common_yes_no" value-to-number></PorDictRadio>
        </NFormItem>
        <NFormItem label="SEO 标题" path="seoTitle">
          <NInput v-model:value="form.seoTitle" placeholder="SEO 标题" />
        </NFormItem>
        <NFormItem label="SEO 关键字" path="seoKeyword">
          <NInput v-model:value="form.seoKeyword" placeholder="SEO 关键字" />
        </NFormItem>
        <NFormItem label="SEO 站点描述" path="seoDescription">
          <NInput v-model:value="form.seoDescription" placeholder="SEO 关键字" />
        </NFormItem>

        <NFormItem label="扩展属性" path="extendProp">
          <NInput v-model:value="form.extendProp" type="textarea" placeholder="扩展属性" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" :loading="submitting" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
